﻿/*
Copyright © 2010 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;

namespace MSBuild.Mercurial.CodePlex
{
    /// <summary>
    /// Extensions for the <see cref="MemberInfo"/> class.
    /// </summary>
    public static class MemberInfoExtensions
    {
        /// <summary>
        /// Extract the Xml comment associated to an element of the
        /// code source.
        /// </summary>
        /// <param name="reference">
        /// The reference.
        /// </param>
        /// <returns>
        /// The associated comment, could be <c>null</c> if there is no
        /// comment associated to this element.
        /// </returns>
        /// <remarks>
        /// Even if this method is designed against the <see cref="MemberInfo"/>
        /// class, it is currently designed to work only on Type and Property.
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="reference"/> parameter is <c>null</c>.
        /// </exception>
        [SuppressMessage(
            "Microsoft.Design",
            "CA1059:MembersShouldNotExposeCertainConcreteTypes",
            Justification = "The interface IXPathNavigeable doesn't provide enought functionalities")]
        public static XmlNode Comment(this MemberInfo reference)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            // The type associated with the reference
            Type type = reference as Type;
            if (type == null)
            {
                type = reference.DeclaringType;
            }

            // The assembly containing the reference - used to find the documentation.
            Assembly assembly = type.Assembly;
            string docFileName = Path.ChangeExtension(assembly.CodeBase, ".xml");

            XmlDocument document = new XmlDocument();
            XmlNamespaceManager manager;
            try
            {
                using (XmlTextReader reader = new XmlTextReader(docFileName))
                {
                    manager = new XmlNamespaceManager(reader.NameTable);
                    document.Load(reader);
                }
            }
            catch (FileNotFoundException)
            {
                return null;
            }

            // The full name of the reference as part of the xml documentation
            string elementName;
            switch (reference.MemberType)
            {
                case MemberTypes.TypeInfo:
                    elementName = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", 'T', type.FullName);
                    break;

                case MemberTypes.Property:
                default:
                    elementName = string.Format(CultureInfo.InvariantCulture, "{0}:{1}.{2}", reference.MemberType.ToString()[0], type.FullName, reference.Name);
                    break;
            }

            string xpath = string.Format(CultureInfo.InvariantCulture, "//member[@name='{0}']", elementName);
            XmlNode node = document.SelectSingleNode(xpath, manager);

            return node;
        }
    }
}
